package com.example.userblog.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.userblog.common.ResultCode;
import com.example.userblog.dao.UserDao;
import com.example.userblog.entity.User;
import com.example.userblog.exception.CustomException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Resource
    private UserDao userDao;
    public List<User> getAll(){
        return
                userDao.selectAll();
    }
    public User userRegister(User user){
        String username=user.getUsername();
        User user1=userDao.findByUsername(username);
        System.out.println(user1);
        //非空检查，如果不是空的，证明该用户已注册
        if(ObjectUtil.isNotEmpty(user1)){
            System.out.println("123");
            throw new CustomException(ResultCode.USER_EXIST_ERROR);
        }
        userDao.insertSelective(user);
        return user;
    }
    public User userLogin(User user){
        String username=user.getUsername();
        String password=user.getPassword();
        Integer role=user.getRole();
        User user1=userDao.findByUsername(username);
        System.out.println(user1);
        if(ObjectUtil.isEmpty(user1)) {
            throw new CustomException(ResultCode.USER_ACCOUNT_ERROR);
        }
        String dbpassword=user1.getPassword();
        if(!password.equalsIgnoreCase(dbpassword)){
            throw new CustomException(ResultCode.USER_ACCOUNT_ERROR);
        }
        Integer dbrole=user1.getRole();
        if(!role.equals(dbrole)){
            throw new CustomException(ResultCode.USER_NOT_EXIST_ERROR);
        }

        return user1;

    }
    public User findById(Integer id){
        return userDao.findById(id);

    }
}
